package com.curd.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.curd.demo.common.Constants;
import com.curd.demo.entity.Menu;
import com.curd.demo.entity.User;
import com.curd.demo.entity.UserDTO;
import com.curd.demo.exception.ServiceException;
import com.curd.demo.mapper.RoleMapper;
import com.curd.demo.mapper.RoleMenuMapper;
import com.curd.demo.mapper.UserMapper;
import com.curd.demo.service.IMenuService;
import com.curd.demo.service.IUserService;
import com.curd.demo.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
//@Service(“beanName”)方便识别
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    //日志打印
    private static final Log LOG = Log.get();

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Override//登录
    public UserDTO login(UserDTO userDTO) {//UserDto是用来接收前端传过来参数写的类，User是根据数据库表结构写出来的类。
        User one = getUserInfo(userDTO);

        if (one != null) {//业务异常，类似账密错误
            BeanUtil.copyProperties(one, userDTO, true);//true忽略大小写

            //设置token
            String toKen = TokenUtils.getToKen(one.getId().toString(), one.getPassword());//让token获取用户id和密码
            userDTO.setToken(toKen);//获取token的值并传值进入DTO

            String role = one.getRole();    //ROLE_ADMIN
            List<Menu> roleMenus = getRoleMenus(role);
            userDTO.setMenus(roleMenus);

            return userDTO;
        } else {
            throw new ServiceException(Constants.C0DE_600, "用户名或密码错误");
        }
    }

    @Override//注册
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);
            save(one);  //把copy完的用户对象储存到数据库当中去
        }else{
            throw new ServiceException(Constants.C0DE_600, "用户已存在");
        }
        return null;
    }


    //上面都需要这个方法，直接封装一个工具类
    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {//系统方面异常，类似数据库脏数据
            one = getOne(queryWrapper);//从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);//将错误信息抛到后台
            throw new ServiceException(Constants.C0DE_500, "系统错误");
        }
        return one;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag){
        Integer roleId = roleMapper.selectByFlag(roleFlag);

        //当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        //查出系统所有菜单
        List<Menu> menus = menuService.findMenus("");
        //new一个筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        //筛选当前用户的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }

            List<Menu> children = menu.getChildren();
            //removeIf() 移除children里面不在menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        System.out.println(roleMenus);
        return roleMenus;
    }
}